package content;

import java.io.*;

import javax.swing.JOptionPane;

public class IOManage {
	
	public static void loadFile(File f){
		if (f.canRead()){
			String file = f.getPath();
			BufferedReader reader;
			try {
				reader = new BufferedReader(new FileReader(file));
				String line = null;
				try {
					//read
					while ((line = reader.readLine()) != null) {
						System.out.println(line);
					}
				} catch (IOException e) {
					System.out.println("File Error");
					}
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			} catch (FileNotFoundException e1) {
				System.out.println("File Not Found");
			}
		} else { 
			System.out.println("File could not be read.");
		}
	}
	
	
	public static void saveFile(File f){
		if (f == null){
			return;
		}
		try{
			saveFileHelper(f);
		} catch (IOException e){
			JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
			return;
		}
		JOptionPane.showMessageDialog(null, "File Saved", "Saved", JOptionPane.INFORMATION_MESSAGE);
	}
	
	
	public static void saveFileHelper(File f) throws IOException{
		if (f.canWrite()){
			String file = f.getPath();
			PrintWriter out;
			try {
				out = new PrintWriter(new BufferedWriter(new FileWriter(file)));
				//write
				out.write("asdf"); //use threads to show a pop up while saving...from StatsGUI/other class
				out.close();
				return;
			} catch (IOException e) {
				throw new IOException("Could Not Write To File");
			}
		} else {
			if (!f.getName().endsWith(".txt")){
				File newF = new File(f.getPath().concat(".txt"));
				f = newF;
			}
			try {
				if (f.createNewFile()){
					saveFile(f);
					System.out.println("Saved.");
					return;
				} else {
					throw new IOException("File could not be written to.");
				}
			} catch (IOException e) {
				throw new IOException("Could not create file");
			}
		}
	}
}
